<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>产品列表</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="productList">
        <el-table-column type="index" width="50" />
        <el-table-column label="产品名称" prop="name" />
        <el-table-column label="产品分类" prop="categoryName" />
        <el-table-column label="价格" prop="price" />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否热门" prop="isHot">
          <template #default="scope">
            <el-tag :type="scope.row.isHot === 1 ? 'danger' : 'info'">
              {{ scope.row.isHot === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="产品图片" prop="productImages" v-if="form.id">
          <el-upload
            :headers="headers"
            list-type="picture-card"
            :on-remove="handleImageRemove"
            :http-request="customUpload"
            :file-list="uploadFileList"
            multiple
            :on-preview="handlePictureCardPreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible" title="预览">
            <el-image
              v-if="previewUrl"
              :src="previewUrl"
              fit="contain"
              style="width: 100%"
            />
          </el-dialog>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-radio-group v-model="form.isHot">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品详情对话框 -->
    <el-dialog title="产品详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="产品类型">{{ getCategoryName(detailData.categoryId) }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{ detailData.price }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ detailData.status === 1 ? '上架' : '下架' }}
        </el-descriptions-item>
        <el-descriptions-item label="是否热门">
          {{ detailData.isHot === 1 ? '是' : '否' }}
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ detailData.description }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="mt20">
        <p class="mb10">产品图片：</p>
        <div class="image-preview-container">
          <el-image
            v-for="(image, index) in detailData.productImages"
            :key="index"
            :src="image.imageUrl"
            :preview-src-list="detailData.productImages.map(img => img.imageUrl)"
            :initial-index="index"
            fit="cover"
            class="preview-image mr10 mb10"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';
import request from '@/utils/request';
import { listProduct, getProduct, addProduct, updateProduct, uploadProductImage } from '@/api/product/product';
import { ProductQuery, ProductForm, ProductVo } from '@/api/product/product/types';

// 查询参数
const queryParams = ref<ProductQuery>({
  pageNum: 1,
  pageSize: 10,
  name: '',
  categoryId: undefined,
  status: undefined
});

// 表单数据
const form = ref<ProductForm>({
  name: '',
  categoryId: undefined,
  price: '',
  description: '',
  status: 1,
  isHot: 0,
  productImages: []
});

// 其他数据
const loading = ref(false);
const total = ref(0);
const open = ref(false);
const detailOpen = ref(false);
const title = ref('');
const productList = ref<ProductVo[]>([]);
const detailData = ref<ProductVo>({} as ProductVo);
const categoryOptions = ref([]);

// 上传相关配置
const uploadImagesUrl = import.meta.env.VITE_APP_BASE_API + '/product/product/uploadImage';
const headers = {
  Authorization: 'Bearer ' + getToken()
};

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择产品分类', trigger: 'change' }],
  price: [
    { required: true, message: '请输入产品价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
  ],
  description: [{ required: true, message: '请输入产品描述', trigger: 'blur' }]
};

// 表单引用
const productRef = ref();

// 上传文件列表
const uploadFileList = ref<any[]>([]);

// 添加图片预览相关变量和方法
const dialogVisible = ref(false);
const previewUrl = ref('');

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    console.log('查询参数:', queryParams.value);
    const res = await listProduct(queryParams.value);
    console.log('API返回数据:', res);
    if (res.code === 200) {
      productList.value = res.rows;
      total.value = res.total;
      console.log('处理后的列表数据:', productList.value);
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    categoryId: undefined,
    status: undefined
  };
  handleQuery();
};

// 新增按钮操作
const handleAdd = () => {
  form.value = {
    name: '',
    categoryId: undefined,
    price: '',
    description: '',
    status: 1,
    isHot: 0,
    productImages: []
  };
  uploadFileList.value = [];  // 清空上传文件列表
  title.value = '添加产品';
  open.value = true;
};

// 修改按钮操作
const handleUpdate = async (row: ProductVo) => {
  const res = await getProduct(row.id);
  if (res.code === 200) {
    form.value = res.data;
    // 确保productImages是一个数组
    if (!form.value.productImages) {
      form.value.productImages = [];
    }
    // 转换图片列表为el-upload需要的格式
    uploadFileList.value = form.value.productImages.map(img => ({
      name: img.imageUrl.substring(img.imageUrl.lastIndexOf('/') + 1),
      url: img.imageUrl
    }));
    console.log('修改操作初始化的productImages:', JSON.stringify(form.value.productImages));
    console.log('修改操作初始化的uploadFileList:', JSON.stringify(uploadFileList.value));
    title.value = '修改产品';
    open.value = true;
  } else {
    ElMessage.error(res.msg || '获取数据失败');
  }
};

// 详情按钮操作
const handleDetail = async (row: ProductVo) => {
  const res = await getProduct(row.id);
  if (res.code === 200) {
    detailData.value = res.data;
    detailOpen.value = true;
  } else {
    ElMessage.error(res.msg || '获取详情失败');
  }
};

// 自定义上传方法
const customUpload = async (params: any) => {
  try {
    const formData = new FormData();
    formData.append('file', params.file);
    
    const productId = form.value.id || 0;
    console.log('开始上传图片，productId:', productId);
    
    const res = await request({
      url: `/product/product/uploadImage/${productId}`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data',
        ...headers
      },
      data: formData
    });

    console.log('上传接口返回的完整响应:', res);

    if (res.code === 200) {
      // 获取上传后的图片信息
      const ossData = res.data;
      console.log('上传成功，获取到的图片信息:', ossData);
      
      // 添加到上传文件列表
      uploadFileList.value.push({
        name: ossData.fileName,
        url: ossData.url,
        ossId: ossData.ossId
      });
      
      // 添加到产品图片列表中
      form.value.productImages.push({
        id: 0,  // 新上传的图片id为0
        productId: form.value.id || 0,
        imageUrl: ossData.url,
        sort: form.value.productImages.length + 1,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createDept: null
      });
      
      ElMessage.success('上传成功');
    } else {
      ElMessage.error(res.msg || '上传失败');
      return false;
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
    return false;
  }
};

// 删除图片
const handleImageRemove = (file: any) => {
  console.log('准备删除图片:', file);
  // 从uploadFileList中删除
  const fileIndex = uploadFileList.value.findIndex(item => item.url === file.url);
  if (fileIndex !== -1) {
    uploadFileList.value.splice(fileIndex, 1);
  }
  // 从productImages中删除
  const index = form.value.productImages.findIndex(item => item.imageUrl === file.url);
  if (index !== -1) {
    form.value.productImages.splice(index, 1);
    // 重新排序
    form.value.productImages.forEach((item, idx) => {
      item.sort = idx + 1;
    });
    console.log('删除后的productImages:', JSON.stringify(form.value.productImages));
  }
};

// 表单提交前检查图片
const validateImages = () => {
  if (form.value.id && form.value.productImages.length === 0) {
    ElMessage.warning('请至少上传一张产品图片');
    return false;
  }
  return true;
};

// 表单提交
const submitForm = async () => {
  if (!productRef.value) return;
  
  await productRef.value.validate(async (valid: boolean) => {
    if (valid && validateImages()) {
      try {
        // 在提交前，确保所有图片信息都是完整的
        const formData = { ...form.value };
        
        // 如果是新增，清空productImages数组
        if (!formData.id) {
          formData.productImages = [];
        } else {
          console.log('提交前的原始数据:', JSON.stringify(formData.productImages));
          
          // 确保productImages是一个数组并且每个图片都有URL
          formData.productImages = formData.productImages.map(img => {
            // 如果已经有URL，直接使用
            if (img.imageUrl) {
              return img;
            }
            // 尝试从uploadFileList中找到对应的URL
            const uploadedFile = uploadFileList.value.find(file => file.url === img.imageUrl);
            if (uploadedFile) {
              return {
                ...img,
                imageUrl: uploadedFile.url
              };
            }
            return img;
          });
        }
        
        console.log('处理后的提交数据:', JSON.stringify(formData.productImages));
        const response = formData.id 
          ? await updateProduct(formData)
          : await addProduct(formData);
        
        if (response.code === 200) {
          ElMessage.success('操作成功');
          open.value = false;
          getList();
        } else {
          ElMessage.error(response.msg || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

// 取消按钮
const cancel = () => {
  open.value = false;
  uploadFileList.value = []; // 清空上传文件列表
  form.value = {
    name: '',
    categoryId: undefined,
    price: '',
    description: '',
    status: 1,
    isHot: 0,
    productImages: []
  };
};

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await request({
      url: '/productIndex/categories',
      method: 'get'
    });
    if (res.code === 200) {
      categoryOptions.value = res.data;
      console.log('获取到的分类列表:', categoryOptions.value);
    } else {
      ElMessage.error(res.msg || '获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
  }
};

// 图片预览
const handlePictureCardPreview = (file: any) => {
  previewUrl.value = file.url;
  dialogVisible.value = true;
};

// 根据分类ID获取分类名称（仅用于详情对话框）
const getCategoryName = (categoryId: number) => {
  const category = categoryOptions.value.find(item => item.id === categoryId);
  return category ? category.name : '';
};

onMounted(() => {
  getList();
  getCategoryList();
});
</script>

<style scoped>
.mr10 {
  margin-right: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
.mt20 {
  margin-top: 20px;
}
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.preview-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}
</style> 